/**
 * 更新equipment_base表base值的脚本
 * 功能：根据装备数据更新equipment_base表中对应装备的base值
 */

const mysql = require('mysql2/promise');

// 数据库连接配置（直接使用正确的配置）
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

// 装备数据映射
const equipmentData = {
    // base=1: 锤类装备
    1: [
        { id: 2, name: "木锤·力", lvl: 1, price: 1500 },
        { id: 7, name: "青铜锤·力", lvl: 2, price: 3000 },
        { id: 8, name: "镔铁锤·力", lvl: 3, price: 6000 },
        { id: 9, name: "精钢锤·力", lvl: 4, price: 12000 },
        { id: 10, name: "乌金锤·力", lvl: 5, price: 24000 },
        { id: 11, name: "混元锤·力", lvl: 6, price: 48000 },
        { id: 12, name: "地煞锤·力", lvl: 7, price: 96000 },
        { id: 13, name: "天罡锤·力", lvl: 8, price: 192000 },
        { id: 14, name: "亮银锤·力", lvl: 9, price: 384000 },
        { id: 15, name: "紫金锤·力", lvl: 10, price: 768000 }
    ],
    // base=2: 斧类装备
    2: [
        { id: 3, name: "木斧·血", lvl: 1, price: 1500 },
        { id: 16, name: "青铜斧·血", lvl: 2, price: 3000 },
        { id: 17, name: "镔铁斧·血", lvl: 3, price: 6000 },
        { id: 18, name: "精钢斧·血", lvl: 4, price: 12000 },
        { id: 19, name: "乌金斧·血", lvl: 5, price: 24000 },
        { id: 20, name: "混元斧·血", lvl: 6, price: 48000 },
        { id: 21, name: "地煞斧·血", lvl: 7, price: 96000 },
        { id: 22, name: "天罡斧·血", lvl: 8, price: 192000 },
        { id: 23, name: "亮银斧·血", lvl: 9, price: 384000 },
        { id: 24, name: "紫金斧·血", lvl: 10, price: 768000 }
    ],
    // base=3: 针类装备
    3: [
        { id: 4, name: "绣花针·精", lvl: 1, price: 1500 },
        { id: 25, name: "枣核钉·精", lvl: 2, price: 3000 },
        { id: 26, name: "冰银针·精", lvl: 3, price: 6000 },
        { id: 27, name: "暖玉针·精", lvl: 4, price: 12000 },
        { id: 28, name: "玉蜂针·精", lvl: 5, price: 24000 },
        { id: 29, name: "梨花针·精", lvl: 6, price: 48000 },
        { id: 30, name: "绫绢扇·精", lvl: 7, price: 96000 },
        { id: 31, name: "竹丝扇·精", lvl: 8, price: 192000 },
        { id: 32, name: "火画扇·精", lvl: 9, price: 384000 },
        { id: 33, name: "檀香扇·精", lvl: 10, price: 768000 }
    ],
    // base=4: 剑类装备
    4: [
        { id: 5, name: "木剑·速", lvl: 1, price: 1500 },
        { id: 34, name: "青铜剑·速", lvl: 2, price: 3000 },
        { id: 35, name: "镔铁剑·速", lvl: 3, price: 6000 },
        { id: 36, name: "精钢剑·速", lvl: 4, price: 12000 },
        { id: 37, name: "乌金剑·速", lvl: 5, price: 24000 },
        { id: 38, name: "混元剑·速", lvl: 6, price: 48000 },
        { id: 39, name: "地煞剑·速", lvl: 7, price: 96000 },
        { id: 40, name: "天罡剑·速", lvl: 8, price: 192000 },
        { id: 41, name: "亮银剑·速", lvl: 9, price: 384000 },
        { id: 42, name: "紫金剑·速", lvl: 10, price: 768000 }
    ],
    // base=5: 刀类装备
    5: [
        { id: 6, name: "木刀·均", lvl: 1, price: 1500 },
        { id: 43, name: "青铜刀·均", lvl: 2, price: 3000 },
        { id: 44, name: "镔铁刀·均", lvl: 3, price: 6000 },
        { id: 45, name: "精钢刀·均", lvl: 4, price: 12000 },
        { id: 46, name: "乌金刀·均", lvl: 5, price: 24000 },
        { id: 47, name: "混元刀·均", lvl: 6, price: 48000 },
        { id: 48, name: "地煞刀·均", lvl: 7, price: 96000 },
        { id: 49, name: "天罡刀·均", lvl: 8, price: 192000 },
        { id: 50, name: "亮银刀·均", lvl: 9, price: 384000 },
        { id: 51, name: "紫金刀·均", lvl: 10, price: 768000 }
    ]
};

class EquipmentBaseUpdater {
    constructor() {
        this.connection = null;
        this.dbConfig = dbConfig;
    }

    // 建立数据库连接
    async connect() {
        try {
            this.connection = await mysql.createConnection(this.dbConfig);
            console.log('✅ 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    // 关闭数据库连接
    async disconnect() {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 检查equipment_base表是否存在
    async checkTableExists() {
        try {
            console.log('🔍 检查equipment_base表是否存在...');
            
            const [rows] = await this.connection.execute(`
                SELECT COUNT(*) as count 
                FROM information_schema.tables 
                WHERE table_schema = '${this.dbConfig.database}' 
                AND table_name = 'equipment_base'
            `);

            const exists = rows[0].count > 0;
            console.log(`📊 equipment_base表${exists ? '存在' : '不存在'}`);
            return exists;
        } catch (error) {
            console.error('❌ 检查表存在性失败:', error.message);
            throw error;
        }
    }

    // 获取当前equipment_base表的数据
    async getCurrentEquipmentData() {
        try {
            console.log('📋 获取当前equipment_base表数据...');
            
            const [rows] = await this.connection.execute(`
                SELECT id, name, base, level, price 
                FROM equipment_base 
                ORDER BY id
            `);

            console.log(`📊 当前表中有 ${rows.length} 条装备数据`);
            return rows;
        } catch (error) {
            console.error('❌ 获取当前装备数据失败:', error.message);
            throw error;
        }
    }

    // 更新装备的base值
    async updateEquipmentBase(baseValue, equipmentList) {
        try {
            console.log(`🔄 开始更新base=${baseValue}的装备数据...`);
            
            let successCount = 0;
            let errorCount = 0;

            for (const equipment of equipmentList) {
                try {
                    const updateSQL = `
                        UPDATE equipment_base 
                        SET base = ?, level = ?, price = ? 
                        WHERE id = ? AND name = ?
                    `;

                    const [result] = await this.connection.execute(updateSQL, [
                        baseValue,
                        equipment.lvl,
                        equipment.price.toString(),
                        equipment.id,
                        equipment.name
                    ]);

                    if (result.affectedRows > 0) {
                        successCount++;
                        console.log(`✅ 更新装备: ${equipment.name} (ID: ${equipment.id}) -> base=${baseValue}, lvl=${equipment.lvl}, price=${equipment.price}`);
                    } else {
                        errorCount++;
                        console.log(`⚠️ 未找到装备: ${equipment.name} (ID: ${equipment.id})`);
                    }
                } catch (error) {
                    errorCount++;
                    console.error(`❌ 更新装备失败 (ID: ${equipment.id}):`, error.message);
                }
            }

            console.log(`📊 base=${baseValue} 更新完成: 成功 ${successCount} 条, 失败 ${errorCount} 条`);
            return { successCount, errorCount };
        } catch (error) {
            console.error(`❌ 更新base=${baseValue}装备失败:`, error.message);
            throw error;
        }
    }

    // 验证更新结果
    async verifyUpdate() {
        try {
            console.log('🔍 验证更新结果...');

            // 按base值分组统计
            const [rows] = await this.connection.execute(`
                SELECT base, COUNT(*) as count, 
                       MIN(level) as min_level, MAX(level) as max_level,
                       MIN(CAST(price AS UNSIGNED)) as min_price, MAX(CAST(price AS UNSIGNED)) as max_price
                FROM equipment_base 
                WHERE base IN (1, 2, 3, 4, 5)
                GROUP BY base 
                ORDER BY base
            `);

            console.log('📋 按base值分组的装备统计:');
            rows.forEach(row => {
                console.log(`   base=${row.base}: ${row.count}个装备, 等级${row.min_level}-${row.max_level}, 价格${row.min_price}-${row.max_price}`);
            });

            // 显示每个base的前3个装备作为示例
            for (let base = 1; base <= 5; base++) {
                const [sampleRows] = await this.connection.execute(`
                    SELECT id, name, base, level, price 
                    FROM equipment_base 
                    WHERE base = ? 
                    ORDER BY level 
                    LIMIT 3
                `, [base]);

                console.log(`📋 base=${base} 前3个装备示例:`);
                sampleRows.forEach(row => {
                    console.log(`   ID: ${row.id}, 名称: ${row.name}, 等级: ${row.level}, 价格: ${row.price}`);
                });
            }

        } catch (error) {
            console.error('❌ 验证更新结果失败:', error.message);
            throw error;
        }
    }

    // 运行完整的更新流程
    async runUpdate() {
        console.log('🚀 开始更新equipment_base表base值...\n');

        try {
            // 1. 连接数据库
            await this.connect();

            // 2. 检查表是否存在
            const tableExists = await this.checkTableExists();
            if (!tableExists) {
                throw new Error('equipment_base表不存在');
            }

            // 3. 获取当前数据
            await this.getCurrentEquipmentData();

            // 4. 更新各个base值的装备
            let totalSuccess = 0;
            let totalError = 0;

            for (const [baseValue, equipmentList] of Object.entries(equipmentData)) {
                const result = await this.updateEquipmentBase(parseInt(baseValue), equipmentList);
                totalSuccess += result.successCount;
                totalError += result.errorCount;
                console.log(''); // 空行分隔
            }

            // 5. 验证更新结果
            await this.verifyUpdate();

            console.log('\n📊 更新完成统计:');
            console.log(`   总成功: ${totalSuccess} 条`);
            console.log(`   总失败: ${totalError} 条`);
            console.log(`   总计: ${totalSuccess + totalError} 条`);

            console.log('\n🎉 equipment_base表base值更新完成！');

        } catch (error) {
            console.error('\n💥 更新过程中发生错误:', error.message);
            throw error;
        } finally {
            // 6. 关闭连接
            await this.disconnect();
        }
    }
}

// 运行更新
async function main() {
    console.log('🎯 equipment_base表base值更新脚本');
    console.log('   功能：根据装备数据更新equipment_base表中对应装备的base值\n');

    const updater = new EquipmentBaseUpdater();
    await updater.runUpdate();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 更新脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = EquipmentBaseUpdater;
